package com.lzc.springboot_jsp_shiro.config;


import com.lzc.springboot_jsp_shiro.shirorealm.CustomerRealm;
import com.lzc.springboot_jsp_shiro.shirorealm.cache.RedisCacheManager;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfiguration {
    /**
     * 1配置shiro过滤器拦截请求
     *
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //配置系统公共资源
        //配置系统受限资源
        Map<String, String> map = new HashMap<>();
        map.put("/user/loginto", "anon");
        map.put("/user/register", "anon");
        map.put("/toregister", "anon");
        map.put("/**", "authc");
        //配置登录url
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    /**
     * 2配置DefaultWebSecurityManager安全管理器处理请求
     *
     * @param realm
     * @return
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    /**
     * 3配置自定义Realm认证和授权
     *
     * @return
     */
    @Bean
    public Realm realm() {
        CustomerRealm customerRealm = new CustomerRealm();
        //修改凭证校验器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //设置为md5加密
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //设置哈希1024次
        hashedCredentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        //开启缓存
        customerRealm.setCachingEnabled(true);
        //使用自定义缓存redis管理
        customerRealm.setCacheManager(new RedisCacheManager());
        //开启认证缓存
        customerRealm.setAuthenticationCachingEnabled(true);
        customerRealm.setAuthenticationCacheName("authentication");
        //开启授权缓存
        customerRealm.setAuthorizationCachingEnabled(true);
        customerRealm.setAuthorizationCacheName("authorization");
        return customerRealm;
    }
}
